import React, { useReducer } from 'react';

const initialUser = { username: '' }; //定义user的默认值

//修改user事件处理函数，根据修改参数进行处理
function reducer(state, action) {
  //注意这里先判断事件类型，然后结合携带的参数param 来最终修改count
  switch (action.type) {
    case 'login':
      return { ...state, ...action.param };
    case 'logout':
      return initialUser;
    default:
      return state;
  }
}

const GlobalContext = React.createContext();

function GlobalProvider({ children }) {
  //定义全局变量count，以及负责抛出修改事件的dispatch
  const [user, dispatch] = useReducer(reducer, initialUser);

  //请注意：value={{user,dispatch} 是整个代码的核心，把将user、dispatch暴露给所有子组件
  return <GlobalContext.Provider value={{ user, dispatch }}>{children}</GlobalContext.Provider>;
}

export { GlobalProvider, GlobalContext };
